<?php	
	require_once('paths.inc');
	
	require_once('page.inc');
	require_once(INCLUDE_PATH.'constants.inc');
	
    require_once(DB_PATH.'db.inc');
	require_once('utils.inc');

	require_once('security.inc');
	require_once('server_validations.inc');
	
	session_start();
	
    unset($_SESSION['user_logat']);
    unset($_SESSION['client_logat']);
	unset($_SESSION['language']);
	
	$appUsername = $_POST["formUsername"];
	$appPassword = $_POST["formPassword"];
	
    select_language();
    
	// Clean the data collected from the user
	if (!validPrintable($appUsername, CT_MIN_USERNAME_LENGTH, CT_MAX_USERNAME_LENGTH)) {
		wrong_auth("LANG_Wrong_User_Password");		    		
	}
	
	if (!validPrintable($appPassword, CT_MIN_PASSWORD_LENGTH, CT_MAX_PASSWORD_LENGTH)) {
		wrong_auth("LANG_Wrong_User_Password");
	}
		
	$crypted_password = User::crypt_password($appUsername, $appPassword);

	$db = db_connect();

	try {		
		$user_data = User::getUserByUserAndPass($db, $appUsername, $crypted_password);
		$client_id = $user_data->id_client;

		$_SESSION['user_logat'] = $user_data;	
		$_SESSION['client_logat'] = Client::queryLoad($db, $client_id);        
		$_SESSION['language'] = $limbi[$user_data->language];		
		
		if ($user_data->change_pass == CT_MUST_CHANGE_PASSWORD) {
			header("Location: change_password.php");
            exit();
        }

		header("Location: home.php");
        exit();
	}
	catch (QueryLoadContException $e) {
		header("Location: site_login.php");
        exit();
	}
	catch (QueryLoadUserException $e) {
        wrong_auth(LANG_Wrong_User_Password);
	}
	catch (QueryLoadClientException $e) {
		header("Location: site_login.php");
        exit();
	}
	catch (QueryLoadAddressException $e) {
		header("Location: site_login.php");
        exit();
	}
?>